<template>
    <div>
        <NoAuthPage v-showNoAuth="'D12-1'" :imgBoxStyle="{ height: '40vh', margin: '0 10px 10px' }" />
        <div v-userAuth="'D12-1'">
            <div style="display: flex;max-height: 730px;">
                <div ref="container" class="left"
                    style="width: 300px;background: #F0F3F5;overflow-y: auto;overflow-x:hidden;" @scroll="handleScroll">
                    <a-spin :spinning="loading">
                        <a-directory-tree :tree-data="treeData" @expand="onExpand" :defaultExpandedKeys="expandedKeys"
                            :replace-fields="{ children: 'children', key: 'id', value: 'name', title: 'name' }" />
                    </a-spin>
                </div>
                <div class="right" style="flex:1;padding-right: 16px;">
                    <div style="height:32px;line-height: 32px;border-bottom: 1px solid #E8E8E8;display: flex;">
                        <a-icon v-if="currentDirectory && currentDirectory !== header"
                            style="margin-left: 8px;margin-top: 10px;cursor: pointer;" type="left"
                            @click="handleNavigate" />
                        <div style="margin-left: 8px;display: flex;">
                            <div style="display: flex;align-items: center;">
                                <div style=";cursor:pointer" @click="directoryClick(header)">{{ header }}</div>
                                <a-icon v-if="directoryList.length !== 0" style="margin-left: 8px;" type="right" />
                                <div style="margin-right: 8px;margin-top: -16px;font-size: 24px;"
                                    v-if="directoryList.length >= 5">
                                    ...</div>
                            </div>
                            <div style="margin-left:8px" v-for="(item, index) of directoryList">
                                <span style="padding:8px;cursor:pointer" @click="directoryClick(item)">{{ item }}</span>
                                <a-icon v-if="index !== 4" type="right" />
                            </div>
                        </div>
                    </div>
                    <div style="margin-top: 12px;margin-left: 16px;">
                        <div style="display: flex;justify-content: space-between;">
                            <a-button v-userAuth="'D12-2'" type='primary' @click="handleCreate">
                                <Iconfont class="icon button-icon-style" type="icon-new16f"></Iconfont>
                                {{ $t('Create') }}
                            </a-button>
                            <div style="display: flex;">
                                <div style="display: flex;">
                                    <div style="width: 100px;margin-top: 4px;">{{ $t('文件名称') }}：</div>
                                    <a-input v-model="input" :placeholder="$t('Enter') + $t('文件名称')" />
                                </div>
                                <a-button type='primary' style="margin-left: 8px;" @click="handleSearch">
                                    <Iconfont class="icon button-icon-style" type="icon-search16f"></Iconfont>
                                    {{ $t('Search') }}
                                </a-button>
                            </div>
                        </div>

                        <a-spin :spinning="loading">
                            <a-table style="margin-top:16px;" class="bigstyle" rowKey="id" :columns='columns'
                                :dataSource='currentChildren' :locale="defaultSetting" :pagination='pagination'
                                size='small'>
                                <template slot="name" slot-scope="name, record">
                                    <span v-if="record.child && record.lv <= 15" style="color: #006DB8;cursor: pointer"
                                        @click="handleDetail(record)">{{ name }}</span>
                                    <span v-else>{{ name }}</span>
                                </template>
                                <template slot="operate" slot-scope='text, record'>
                                    <div style="display: flex;justify-content: space-between;">
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span>{{ $t('创建共享') }}</span>
                                            </template>
                                            <Iconfont v-userAuth="'D19-3'" class="icon table-operation-icon"
                                                type="icon-share16f" @click="handleShare(record)">
                                            </Iconfont>
                                        </a-tooltip>
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span>{{ $t('创建配额') }}</span>
                                            </template>
                                            <Iconfont v-userAuth="'D25-2'" class="icon table-operation-icon"
                                                type="icon-quota16f1" @click="handleQuota(record)">
                                            </Iconfont>
                                        </a-tooltip>
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span>{{ $t('Set-pool') }}</span>
                                            </template>
                                            <Iconfont v-userAuth="'D12-4'" class="icon table-operation-icon"
                                                type="icon-pool16f" @click="handlePool(record)">
                                            </Iconfont>
                                        </a-tooltip>
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span>{{ $t('快照配置') }}</span>
                                            </template>
                                            <Iconfont class="icon table-operation-icon" v-userAuth="'D13'"
                                                type="icon-photo16f" @click="handleSnapshot(record)">
                                            </Iconfont>
                                        </a-tooltip>
                                        <a-tooltip placement='top'>
                                            <template slot='title'>
                                                <span>{{ $t('Delete') }}</span>
                                            </template>
                                            <Iconfont v-userAuth="'D12-5'" class="icon table-operation-icon"
                                                type="icon-delete16f" @click="handleDelete(record)"></Iconfont>
                                        </a-tooltip>
                                    </div>
                                </template>
                            </a-table>
                        </a-spin>
                    </div>
                </div>

                <createDirectory ref="createRef" @get-list="getList" />
                <PoolDialog ref="poolRef" @get-list="getList" />
                <ShareDialog ref="shareRef" @change-tab="handleTab" />

            </div>
            <div
                style="height: 20px;line-height: 20px;text-align: center;width: 300px;background: #F0F3F5;border-top: 1px solid #E8E8E8">
                {{ bottomContent }}
            </div>
        </div>
    </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import createDirectory from './createDirectory.vue'
import PoolDialog from './poolDialog'
import ShareDialog from './shareDialog.vue'
import NoAuthPage from '@/components/common/NoAuthPage'

export default {
    components: { createDirectory, EmptyData, PoolDialog, ShareDialog, NoAuthPage },
    data() {
        return {
            treeData: [],
            copyList: [],
            expandedKeys: [],
            currentDirectory: '',
            currentChildren: [],
            input: '',
            loading: false,
            page: 1,
            file_path: '',
            defaultSetting: { emptyText: <EmptyData /> },
            pagination: {
                current: 1,
                pageSize: 25,
                total: 0,
                // defaultPageSize: 25,
                showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '25', '50'],
                onShowSizeChange: async (page, page_size) => {
                    this.pagination.current = page
                    this.pagination.pageSize = page_size
                    this.loading = true
                    const { data } = await this.$api.directory.getDirectoryListApi({ file_path: this.file_path, page, page_size })
                    this.currentChildren = data[0].children
                    this.copyList = data[0].children
                    this.loading = false
                },
                onChange: async (page, page_size) => {
                    this.pagination.current = page
                    this.pagination.pageSize = page_size
                    this.loading = true
                    const { data } = await this.$api.directory.getDirectoryListApi({ file_path: this.file_path, page, page_size })
                    this.currentChildren = data[0].children
                    this.copyList = data[0].children
                    this.loading = false
                },
                buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            },
            columns: [
                { title: this.$t('名称'), dataIndex: 'name', key: 'name', scopedSlots: { customRender: 'name' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 200 }
            ],
            header: '',
            directoryList: [],
            initData: [],
            directoryItem: {},
            treePage: 2,
            isBottom: true,
        }
    },
    computed: {
        path() {
            const list = this.currentDirectory.split('/')
            if (list.length == 2) return list.slice(2).join('/')
            else if (list.length > 2) return '/' + list.slice(2).join('/')
        },
        bottomContent() {
            if (this.isBottom) return this.$t('没有更多数据了')
            else return this.$t('往下加载更多数据')
        }
    },
    watch: {
        currentDirectory(value) {
            const list = value.split('/').slice(1).filter(item => '/' + item !== this.header).slice(-5)
            this.directoryList = list
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        async getList(file_path = '', isRefresh = false) {
            this.loading = true
            const { data } = await this.$api.directory.getDirectoryListApi({
                page: this.pagination.current,
                page_size: this.pagination.pageSize,
                file_path: this.file_path,
            })
            if (file_path === '') {
                this.header = data[0].name
                this.initData = data[0].children
                this.currentDirectory = this.header
            }
            if (!isRefresh) {
                const itemList = data.map(item => {
                    item.id = 0
                    this.expandedKeys.push(0)
                    return item
                })
                this.treeData = itemList
                if (data[0].total_size > itemList[0].children.length) this.isBottom = false
            }
            this.initData = data[0].children
            this.pagination.total = data[0].total_size
            this.currentChildren = data[0].children
            this.copyList = data[0].children
            const path = this.currentDirectory.split('/').slice(-1)
            this.directoryItem[path] = data[0].children
            this.loading = false
        },
        async onSelect(keys, event) {
            this.loading = true
            const dom = event.selectedNodes[0].dataRef
            const child = dom.child
            let level = dom.lv
            let value = dom.name
            let parent = dom.pre_dir
            let file_path = ''
            if (level == '1') file_path = value
            if (Number(level) > 1) file_path = parent + '/' + value
            this.file_path = file_path
            if (child) {
                const { data } = await this.$api.directory.getDirectoryListApi({
                    page: this.pagination.current,
                    page_size: this.pagination.pageSize,
                    file_path
                })
                this.pagination.total = data[0].total_size
                this.currentChildren = data[0].children
                this.copyList = data[0].children
                this.currentDirectory = this.header + parent + value
            }
            else if (dom.children) {
                this.currentDirectory = this.header
                this.currentChildren = dom.children
                this.copyList = dom.children
            } else {
                this.currentChildren = []
                this.copyList = []
                this.currentDirectory = this.header + parent + value
            }
            this.loading = false
        },
        async onExpand(list, event) {
            const dom = event.node.dataRef
            const child = dom.child
            let level = dom.lv
            let value = dom.name
            let parent = dom.pre_dir
            let file_path = ''
            if (level == '1') file_path = value
            if (Number(level) > 1) file_path = parent + '/' + value
            this.file_path = file_path
            this.loading = true
            if (dom.name == this.header && event.expanded) this.getList()
            else {
                if (child) {
                    const { data } = await this.$api.directory.getDirectoryListApi({
                        page: this.pagination.current,
                        page_size: this.pagination.pageSize,
                        file_path
                    })
                    this.currentChildren = data[0].children
                    this.currentDirectory = this.header + '/' + value
                    this.copyList = data[0].children
                    this.preChildren = data[0].children
                }
            }
            this.loading = false
        },
        handleCreate() {
            this.$refs.createRef.isShow = true
            this.$refs.createRef.form.dir_name = this.path
        },
        handleShare(item) {
            this.$refs.shareRef.isShow = true
            this.$refs.shareRef.form.dir_name = this.path + '/' + item.name
        },
        handleSnapshot(item) {
            localStorage.setItem('fs_current_tab', "FS_Directory");
            this.$router.push({ path: '/snapshotConfig', query: { name: this.path + '/' + item.name } })
        },
        handleQuota(item) {
            localStorage.setItem('fs_current_tab', "FS_Directory");
            this.$router.push({ path: '/createQuota', query: { name: this.path + '/' + item.name } })
        },
        handleTab(item) {
            this.$emit('to-share', item)
        },
        async handlePool(item) {
            this.$refs.poolRef.isShow = true
            this.$refs.poolRef.getList()
            this.$refs.poolRef.form.fs_name = item.fs_name
            this.$refs.poolRef.form.dir_name = this.path + '/' + item.name
            this.$refs.poolRef.form.data_pool = item.data_pool
        },
        async handleDetail(item) {
            this.loading = true
            let file_path
            const { name, pre_dir, lv } = item
            if (lv == '1') file_path = name
            if (Number(lv) > 1) file_path = pre_dir + '/' + name
            this.file_path = file_path
            const { data } = await this.$api.directory.getDirectoryListApi({
                file_path
            })
            this.pagination.current = 1
            this.pagination.pageSize = 25
            this.pagination.total = data[0].total_size
            this.currentChildren = data[0].children
            this.copyList = data[0].children
            this.currentDirectory = this.currentDirectory + '/' + name
            const path = this.currentDirectory.split('/').slice(-1)
            this.directoryItem[path] = data[0].children
            this.loading = false
        },
        async handleDelete(record) {
            this.loading = true
            let _this = this
            this.$confirm({
                title: this.$t('删除文件'),
                content: this.$t('删除文件名为') + `${record.name}` + this.$t('后，将无法恢复！您确定要删除吗？'),
                cancelText: this.$t('Cancel'),
                okText: this.$t('Sure'),
                okType: 'danger',
                icon: 'close-circle',
                async onOk() {
                    const { data } = await _this.$api.directory.deleteDirectoryApi({ dir_name: _this.path + '/' + record.name })
                    _this.model(data.id) //返回模板
                    _this.notice(data.id, data.params, data.flag) //通知列表显示
                    if (data.flag == '0') {
                        _this.getList(record.pre_dir, true)
                    }
                },
                onCancel() {
                }
            })
            this.loading = false
        },
        async handleNavigate() {
            this.pagination.current = 1
            this.pagination.pageSize = 25
            // const { data } = await this.$api.directory.getDirectoryListApi({
            //     file_path: this.file_path
            // })
            const path = this.currentDirectory.split('/').slice(0, this.currentDirectory.split('/').length - 1).join('/')
            const index = path.split('/').slice(-1)
            if (path == this.header) {
                this.copyList = this.initData
                this.currentChildren = this.initData
                this.currentDirectory = this.header
                this.pagination.total = this.initData.length
                this.file_path = ''
            }
            else {
                console.log('directory', this.directoryItem)
                this.copyList = this.directoryItem[index]
                this.currentChildren = this.directoryItem[index]
                this.pagination.total = this.directoryItem[index].length
                this.currentDirectory = path
                this.file_path = path.split('/').slice(2).join('/')
            }
            // this.pagination.total = data[0].total_size
        },
        async directoryClick(directory) {
            this.pagination.current = 1
            this.pagination.pageSize = 25
            if (directory == this.header) {
                this.copyList = this.initData
                this.currentChildren = this.initData
                this.pagination.total = this.initData.length
                this.currentDirectory = this.header
                this.file_path = ''
            } else {
                const index = this.currentDirectory.split('/').findIndex(item => item == directory)
                const path = this.currentDirectory.split('/').slice(0, index + 1).join('/')
                this.copyList = this.directoryItem[directory]
                this.currentChildren = this.directoryItem[directory]
                this.pagination.total = this.directoryItem[directory].length
                this.currentDirectory = path
                this.file_path = path.split('/').slice(2).join('/')
                // this.loading = true
                // const { data } = await this.$api.directory.getDirectoryListApi({
                //     file_path: this.file_path
                // })
                // this.pagination.total = data[0].total_size
                // this.loading = false
            }
        },
        async handleSearch() {
            this.loading = true
            const list = []; // 用于存放搜索出来数据的新数组
            if (this.input) {
                this.copyList.filter((item) => {
                    if (item.name.indexOf(this.input) !== -1) {
                        list.push(item);
                    }
                });
                this.currentChildren = list;
            } else {
                this.currentChildren = this.copyList
                this.pagination.total = this.copyList.length
            }
            this.loading = false
        },
        async handleScroll() {
            const container = this.$refs.container
            const scrollHeight = container.scrollHeight
            const scrollTop = container.scrollTop
            const clientHeight = container.clientHeight
            if (scrollTop + clientHeight >= scrollHeight && !this.loading && !this.isBottom) {
                this.loading = true
                const { data } = await this.$api.directory.getDirectoryListApi({
                    page: this.treePage,
                    page_size: 25,
                })
                const list = [...this.treeData[0].children, ...data[0].children]
                // Object.freeze(this.treeData[0].children = list)
                if (data[0].children.length == 0) this.isBottom = true
                if (list.length >= data[0].total_size) this.isBottom = true
                this.treePage++
                this.loading = false
            }
        },
    },
}
</script>

<style lang="scss" scoped>
::v-deep .ant-tree.ant-tree-directory {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 300px;
}

::v-deep .ant-table-small {
    overflow-y: auto;
    max-height: 600px;
}
</style>